<?php
/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author    yuan1994 <tianpian0805@gmail.com>
 * @link      http://tpadmin.yuan1994.com/
 * @copyright 2016 yuan1994 all rights reserved.
 * @license   http://www.apache.org/licenses/LICENSE-2.0
 */

namespace app\admin\controller;

use app\admin\Controller;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Zone;

class Upload extends Controller
{
    /**
     * 首页
     */
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 文件上传
     */
    public function upload()
    {
        $file = $this->request->file('file');
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path);
        if (!$info) {
            return ajax_return_error($file->getError());
        }
        $data = $this->request->root() . '/tmp/uploads/' . $info->getSaveName();
        $insert = [
            'cate'     => 3,
            'name'     => $data,
            'original' => $info->getInfo('name'),
            'domain'   => '',
            'type'     => $info->getInfo('type'),
            'size'     => $info->getInfo('size'),
            'mtime'    => time(),
        ];
        Db::name('File')->insert($insert);

        return ajax_return(['name' => $data]);
    }

    /**
     * 远程图片抓取
     */
    public function remote()
    {
        $url = $this->request->post('url');
        // validate
        $name = ROOT_PATH . 'public/tmp/uploads/' . get_random();
        $name = \File::downloadImage($url, $name);

        $ret = $this->request->root() . '/tmp/uploads/' . basename($name);

        return ajax_return(['url' => $ret], '抓取成功');
    }

    /**
     * 图片列表
     */
    public function listImage()
    {
        $page = $this->request->param('p', 1);
        if ($this->request->param('count')) {
            $ret['count'] = Db::name('File')->where('cate=3')->count();
        }
        $ret['list'] = Db::name('File')->where('cate=3')->field('id,name,original')->page($page, 10)->select();

        return ajax_return($ret);
    }

    public function uploadImgs () {

        if ($this->request->isPost()) {
            $accessKey = '_Nuin9XgMEg5AOopLmEMsTQZHKpBpZo3iriC-bXo';
            $secretKey = 'VGbmzAubnoyR_wcChcWbnMwFgHsHH5i9HWvY_pLN';
            $bukect = 'imgs';
            $domain = 'http://p676ucr27.bkt.clouddn.com';
            //获取文件
            $file = request()->file('file');
            // 要上传图片的本地路径
            $filePath = $file->getRealPath();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            //获取当前控制器名称
//            $controllerName=$this->getContro();
            // 上传到七牛后保存的文件名
            $key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
            //文件引入
            require_once APP_PATH . '/../vendor/qiniu/php-sdk/autoload.php';
            $auth = new Auth($accessKey, $secretKey);
            // 要上传的空间
            $bucket = $bukect;
            $domain = $domain;

            $token = $auth->uploadToken($bucket,$key,$expires = 3600,$policy = null, $strictPolicy = true);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            $ret = $uploadMgr->putFile($token, $key, $filePath);

            if ($ret === null) {
                $data = [
                    "success"=>0,
                    "msg"=>"上传失败",
                    "data"=>[],
                ];
            } else {
                //返回图片的完整URL
                $data = [
                    "success"=>1,
                    "msg"=>"上传完成",
                    'url' => $domain .'/'. $ret[0]['key'],
                ];
            }
            return json($data);
        }
//        // 获取表单上传文件 例如上传了001.jpg
//        $file = request()->file('file');
//
//        // 移动到框架应用根目录/public/uploads/ 目录下
//        if($file){
//            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads', '');
//
//            if(!$info) return ajax_return_error($file->getError());
//
//            $data = '/public/' .  "uploads/" . $info->getSaveName();
//            $data = [
//                'success' => true,
//                'url' => $data,
//            ];
//            return json($data);
//        }else {
//            return ajax_return_error($file->getError());
//        }
//        return json($file);
    }

    public function uploadFile () {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 获取表单上传文件 例如上传了001.jpg
            $file = $this->request->file('path');

            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads', '');

                if(!$info) return ajax_return_error($file->getError());

                $url = '/var/www/html/downfile/public/' .  "uploads/" . $info->getSaveName();

                $insert = [
                    'name' => $param['name'],
                    'imgpath' => $param['imgpath'],
                    'path' => $url,
                    'type' => $param['type'],
                    'xinghao' => $param['xinghao'],
                    'tuzhibianhao' => $param['tuzhibianhao'],
                    'chanpingbianhao' => $param['chanpingbianhao'],
                    'caizhi' => $param['caizhi'],
                    'zhongliang' => $param['zhongliang'],
                    'bom' => $param['bom'],
                    'remark' => $param['remark'],
                    'stype' => $param['stype'],
                    'create' => time(),
                ];
                $res = Db::name('files')->insert($insert);
               if ($res) {
                   $data = [
                       'success' => true,
                       'msg' => '成功',
                       'data' => [],
                   ];
                }else{
                   $data = [
                       'success' => false,
                       'msg' => '失败',
                       'data' => [],
                   ];
               }

            }else {
                $data = [
                    'success' => false,
                    'msg' => '失败',
                    'data' => [],
                ];
            }
            return json($data);
        }
    }

    public function updateFile () {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 获取表单上传文件 例如上传了001.jpg
            $file = $this->request->file( 'path');

            $map = ['id' => $param['id']];
            $insert = [
                'name' => $param['name'],
                'imgpath' => $param['imgpath'],
                'type' => $param['type'],
                'xinghao' => $param['xinghao'],
                'tuzhibianhao' => $param['tuzhibianhao'],
                'chanpingbianhao' => $param['chanpingbianhao'],
                'caizhi' => $param['caizhi'],
                'zhongliang' => $param['zhongliang'],
                'bom' => $param['bom'],
                'stype' => $param['stype'],
                'remark' => $param['remark'],
                'create' => time(),
            ];
            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads', '');

                if(!$info) return ajax_return_error($file->getError());

                $url = '/var/www/html/downfile/public/' .  "uploads/" . $info->getSaveName();
                $insert['path'] = $url;

            }else {
                $insert['path'] = $param['path'];
            }
            $res = Db::name('files')->where($map)->update($insert);
            if ($res) {
                $data = [
                    'success' => true,
                    'msg' => '成功',
                    'data' => [],
                ];
            }else{
                $data = [
                    'success' => false,
                    'msg' => '失败',
                    'data' => [],
                ];
            }
            return json($data);
        }
    }

    /**
     * 数据排序
     * @return array
     * @throws \Exception
     */
    public function fileSort () {
        if ($this->request->isPost()) {
            $param = $this->request->param();

            $categoryids = $param['categoryids'];
//            print_r($categoryids);
//            die();
            $categoryidsArr = explode(",",$categoryids);
            foreach ($categoryidsArr as $k => $v) {
                $data['sort'] = count($categoryidsArr) - $k;
                $data['id'] = $v;
                Db::name('files')->where(array('id'=>$v))->update($data);
            }
            exit('1');

////            $batch = $param['sorts'];
//
//            $batch = explode($param['sorts'], ',');
//
//            $batch = json_decode($batch, 'utf-8');
//            $ids = array_column($batch,'id');
//            $ids = implode(',',$ids);
//            $sql = 'update tp_files set sort = case id ';
//            foreach ($batch as $key => $val) {
//                $sql .= sprintf("WHEN %d THEN %d ", $val['id'], $val['sort']);
//            }
//            $sql .= "END WHERE id IN ($ids)";
//            $res = Db::query($sql);
            var_dump($res);
            die();
//            if (!$res) {
//                return [
//                    'msg' => '失败',
//                    'success' => false,
//                    'data' => [],
//                ];
//            } else {
//                return [
//                    'msg' => '成功',
//                    'success' => true,
//                    'data' => [],
//                ];
//            }
        }
    }

    /**
     * 获取二级导航列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSecondMenu () {
        if ($this->request->isPost()) {
            $param = $this->request->param();

            $where = [
                'parent_id' => $param['parent_id'],
                'status' => 1,
            ];
            // print_r($param);
            // die;
            $data = Db::name('typefile')->where($where)->field('id, name ')->select();

            if (!$data) {
                return [
                    'msg' => '失败',
                    'success' => false,
                    'data' => [],
                ];
            } else {
                return [
                    'msg' => '成功',
                    'success' => true,
                    'data' => $data,
                ];
            }
        }
    }
}